<template>
  <a-modal title-align="start" title="修改定制信息" :mask-closable="false" v-model:visible="showvisible" @cancel="showvisible = false" :width="900">
    <a-form auto-label-width ref="formRef" size="medium" :model="form">
      <a-row>
        <a-col :span="11">
          <a-form-item label="定制类型">
            <a-select allow-search placeholder="请选项" v-model="form.customType">
              <a-option v-for="(item, index) of customType" :key="index" :label="item" :value="item"></a-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="11" :offset="1">
          <a-form-item label="刻字内容">
            <a-input v-model="form.fontTxt" placeholder="请输入刻字内容" allow-clear />
          </a-form-item>
        </a-col>
        <a-col :span="11">
          <a-form-item label="字体">
            <a-input v-model="form.fontFamily" placeholder="请输入字体" allow-clear />
          </a-form-item>
        </a-col>
        <a-col :span="11" :offset="1">
          <a-form-item label="材质">
            <a-select allow-search placeholder="请选项" v-model="form.material">
              <a-option v-for="(item, index) of materialList" :key="index" :label="item" :value="item"></a-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="11">
          <a-form-item label="电镀颜色">
            <a-input v-model="form.platinColor" placeholder="请输入电镀颜色" allow-clear />
          </a-form-item>
        </a-col>
        <a-col :span="11" :offset="1">
          <a-form-item label="戒指尺码">
            <a-select allow-search placeholder="请选项" v-model="form.ringSize">
              <a-option v-for="(item, index) of ringSizelList" :key="index" :label="item" :value="item"></a-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="11">
          <a-form-item label="石头">
            <a-input v-model="form.stone" placeholder="请输入" allow-clear />
          </a-form-item>
        </a-col>
        <a-col :span="11" :offset="1">
          <a-form-item label="链条">
            <a-select v-model="form.chainList" max-tag-count="1" :loading="selectLoading" placeholder="请选择" multiple @search="handleSearch" :filter-option="false" :show-extra-options="false">
              <a-option v-for="(item, index) of fittingList" :key="index" :value="item.fittingSku" :label="item.fittingName"></a-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="11">
          <a-form-item label="字印">
            <a-select allow-search placeholder="请选项" v-model="form.fontPrint">
              <a-option v-for="(item, index) of fontPrintingList" :key="index" :label="item" :value="item"></a-option>
            </a-select>
          </a-form-item>
        </a-col>

        <a-col :span="11" :offset="1">
          <a-form-item label="备注">
            <a-input v-model="form.remark" placeholder="请输入" allow-clear />
          </a-form-item>
        </a-col>

        <a-col :span="11">
          <a-form-item label="定制图">
            <a-space>
              <a-upload class="fl" v-loading="uplaodfixPicLoading" :show-file-list="false" list-type="picture-card" action="/" :on-before-upload="uploadBefore" />
              <a-image-preview-group infinite>
                <a-space wrap>
                  <div class="img-container" v-for="(item, index) of imgList" :key="index">
                    <icon-close-circle class="del-icon cursor" @click="imgList.splice(index, 1)" />
                    <a-image class="mr10 mb10" :src="item.url" width="80" height="80" />
                  </div>
                </a-space>
              </a-image-preview-group>
            </a-space>
          </a-form-item>
        </a-col>

        <a-col :span="11" :offset="1">
          <a-form-item label="合并图">
            <div>
              <div>
                <a-button type="text" :loading="createImgLoading" @click="createMergeImg">生成合并图</a-button>
              </div>
              <a-image width="80" height="80" :src="mergeCustomPic.url" />
            </div>
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>

    <template #footer class="modal-footer">
      <a-button @click="showvisible = false">取消</a-button>
      <a-button type="primary" :loading="submitLoading" @click="submit">确定</a-button>
    </template>
  </a-modal>
</template>

<script lang="ts" setup>
  import { defineComponent, ref, computed, onMounted } from 'vue'
  import { materialList, customType, fontPrintingList, ringSizelList } from '../../map'
  import { OSSUpload } from '@/utils/ossUpload'
  import { mergeCustomPics, batchUpdateCustomInfo, listFittingPost } from '@/api/purchase'
  import _ from 'lodash-es'
  import { Message } from '@arco-design/web-vue'
  let props = defineProps(['modelValue', 'type', 'info'])
  let emits = defineEmits(['save', 'update:modelValue'])
  const formRef = ref()
  let showvisible = computed({
    get() {
      return props.modelValue
    },
    set(val) {
      emits('update:modelValue', val)
    },
  })
  let form = ref({
    chainList: [],
    customType: '',
    fontTxt: '',
    fontFamily: '',
    material: '',
    platinColor: '',
    ringSize: '',
    stone: '',
    fontPrint: '',
    remark: '',
  })

  let imgList = ref<Array<any>>([])
  let fittingList = ref<Array<any>>([])
  let mergeCustomPic = ref({})
  let uplaodfixPicLoading = ref(false)
  let createImgLoading = ref(false)
  let submitLoading = ref(false)
  let selectLoading = ref(false)

  const submit = async () => {
    let obj = _.cloneDeep(props.info)

    let newCustomInfo = {
      ...form.value,
      customPicList: imgList.value,
      mergeCustomPic: mergeCustomPic.value,
    }

    let chainList = newCustomInfo.chainList || []
    let newFittingList = []
    chainList.forEach((item: any) => {
      let fittItem = fittingList.value.find((fitting: any) => fitting.fittingSku == item)
      if (fittItem) newFittingList.push(fittItem)
    })

    newCustomInfo.chainList = newFittingList

    obj.customInfo = newCustomInfo

    let params = {
      list: [obj],
    }
    try {
      submitLoading.value = true
      await batchUpdateCustomInfo(params)
      Message.success('定制信息修改成功')
      showvisible.value = false
      emits('save')
    } catch (error) {}
    submitLoading.value = false
  }

  const uploadBefore = async (file: File) => {
    try {
      uplaodfixPicLoading.value = true
      const res: any = await OSSUpload(file)
      if (res) {
        let obj = {
          url: res.url,
        }

        imgList.value.push(obj)
      }
    } catch (error) {}
    uplaodfixPicLoading.value = false
  }

  const createMergeImg = async () => {
    let params = {
      customInfo: {
        customPicList: imgList.value,
      },
    }
    try {
      createImgLoading.value = true
      const res = await mergeCustomPics(params)
      mergeCustomPic.value.url = res?.data
    } catch (error) {}
    createImgLoading.value = false
  }

  const getFit = async (searchKey?: string) => {
    let params = {
      catIds: ['cefb90e026fe44a38dece1c482b9bfd8', 'cefb90e026fe44a38dece1c482b9bfd8', '1678781419720RFOqTp8E'],
      searchKey: searchKey,
      ownerCompanyId: 'test_company_id',
      pageNum: 1,
      pageSize: 50,
      pdType: 'fitting',
      searchType: 'dim',
    }
    const res = await listFittingPost(params)
    let arr = res?.result?.list || []

    let newArr = _.cloneDeep(props.info?.customInfo?.chainList)

    fittingList.value = arr.map((e) => {
      e.fittingName = e.productName
      e.fittingSku = e.productSku
      return e
    })

    newArr.forEach((e: any) => {
      let index = fittingList.value.findIndex((el: any) => e.fittingSku === el.fittingSku)
      if (index == -1) fittingList.value.push(e)
    })
  }

  const handleSearch = (value: string) => {
    if (value) {
      selectLoading.value = true
      getFit(value)
      selectLoading.value = false
    } else {
      setInitChain()
    }
  }

  const setInitChain = () => {
    let newArr = props.info?.customInfo?.chainList
    newArr.forEach((e: any) => {
      let index = fittingList.value.findIndex((el: any) => e.fittingSku === el.fittingSku)
      if (index == -1) fittingList.value.push(e)
    })

    form.value.chainList = newArr.map((e: any) => e.fittingSku)
  }

  const init = async () => {
    form.value = _.cloneDeep(props.info).customInfo
    imgList.value = _.cloneDeep(props.info).customInfo?.customPicList || []
    mergeCustomPic.value = _.cloneDeep(props.info).customInfo?.mergeCustomPic || {}
    setInitChain()
  }

  onMounted(init)
</script>

<style lang="less" scoped>
  .img-container {
    position: relative;
    .del-icon {
      position: absolute;
      top: 0;
      right: 0;
      font-size: 16px;
      font-weight: 700;
      z-index: 1;
    }
  }
</style>
